$(function(){
	$.fn.clearFileId = function(){
		var v_itemId = $(this).attr("id");
		$("#"+ v_itemId+"_hidden").val("");
		$("#"+ v_itemId + "_img_queue").html("");
	}
	
	$.fn.setFileId = function(fid,multi,showImage,showBtn,bestSize) {
		var v_itemId = $(this).attr("id");
		if(fid == null) fid = '';
		var ids = $("#"+ v_itemId+"_hidden").val();
		if(ids == undefined || ids == '' || !multi){
			$("#"+ v_itemId+"_hidden").val(fid);
		}else{
			if(fid.indexOf(",")>-1){
				$("#"+ v_itemId+"_hidden").val(fid);
			}else{
				$("#"+ v_itemId+"_hidden").val(ids+","+fid);
			}
		}
		var showBtn = showBtn||false;
		var bestSize = bestSize||'';
		if(fid.length>0){
			if(showImage){
				if(multi){
					var array = fid.split(",");
					for ( var i = 0; i < array.length; i++) {
						$("#"+ v_itemId + "_img_queue").append("<div class='uploadify-img-queue-div'>" + 
							po.showImg({id:array[i],width:60,height:60,parent:true,showBtn:showBtn,bestSize:bestSize,uploadId:v_itemId}) +
							"<a class='uploadify-img-queue-div-a' href='javascript:void(0)' onclick='$(\"#"+v_itemId+"\").delFileId(\""+array[i]+"\","+multi+");$(this).parent().remove();'></a></div>");
					}
				}else{
					$("#"+ v_itemId + "_img_queue").html("<div class='uploadify-img-queue-div'>" + 
							po.showImg({id:fid,width:60,height:60,parent:true,showBtn:showBtn,bestSize:bestSize,uploadId:v_itemId}) +
							"<a class='uploadify-img-queue-div-a' href='javascript:void(0)' onclick='$(\"#"+v_itemId+"\").delFileId(\""+fid+"\","+multi+");$(this).parent().remove();'></a></div>");
				}
			}else{
				if(multi){
					var array = fid.split(",");
					for ( var i = 0; i < array.length; i++) {
						$("#"+ v_itemId + "_img_queue").append("<div class='uploadify-img-queue-div'>" + 
								"<img src=\""+sy.basePath+"/static/manager/libs/uploadifive/file.png\" style=\"width: 60px; height: 60px;\">"+
							"<a class='uploadify-img-queue-div-a' href='javascript:void(0)' onclick='$(\"#"+v_itemId+"\").delFileId(\""+array[i]+"\","+multi+");$(this).parent().remove();'></a></div>");
					}
				}else{
					$("#"+ v_itemId + "_img_queue").html("<div class='uploadify-img-queue-div'>" + 
							"<img src=\""+sy.basePath+"/static/manager/libs/uploadifive/file.png\" style=\"width: 60px; height: 60px;\">"+
							"<a class='uploadify-img-queue-div-a' href='javascript:void(0)' onclick='$(\"#"+v_itemId+"\").delFileId(\""+fid+"\","+multi+");$(this).parent().remove();'></a></div>");
				}
			}
			
		}
	};
	
	$.fn.delFileId = function(fid,multi) {
		var v_itemId = $(this).attr("id");
		var ids = $("#"+ v_itemId+"_hidden").val();
		if(ids == undefined || ids == '' || !multi){
			$("#"+ v_itemId+"_hidden").val("");
		}else{
			var array = ids.split(",");
			for ( var i = 0; i < array.length; i++) {
				if(array[i] == fid){
					array.splice(i,1);
					break;
				}
			}
			ids=array.join(",");
			$("#"+ v_itemId+"_hidden").val(ids);
		}
	};
	
	$.fn.getFileId = function() {
		var v_itemId = $(this).attr("id");
		var ids = $("#"+ v_itemId+"_hidden").val();
		if(ids == undefined || ids == ''){
			return '';
		}else{
			return ids;
		}
	};
	
	$.fn.replaceFileId = function(old,newId,multi,showImage,bestSize,v_itemid) {
		var v_itemId = $(this).attr("id");
		var ids = $("#"+ v_itemId+"_hidden").val();
		var bestSize = bestSize||'';
		if(ids == undefined || ids == ''){
			$("#"+ v_itemId+"_hidden").val("");
		}else{
			var array = ids.split(",");
			for ( var i = 0; i < array.length; i++) {
				if(array[i] == old){
					array[i]=newId;
					break;
				}
			}
			ids=array.join(",");
			$("#"+ v_itemId+"_hidden").val(ids);
		}
		$("#"+ v_itemId + "_img_queue").html("");//清空当前队列
		if(ids.length>0){
			var array = ids.split(",");
			for ( var i = 0; i < array.length; i++) {
				if(showImage){
					$("#"+ v_itemId + "_img_queue").append("<div class='uploadify-img-queue-div'>" + 
							"<img src=\""+sy.basePath+"/static/manager/libs/uploadifive/file.png\" style=\"width: 60px; height: 60px;\">"+
							"<a class='uploadify-img-queue-div-a' href='javascript:void(0)' onclick='$(\"#"+v_itemId+"\").delFileId(\""+array[i]+"\","+multi+");$(this).parent().remove();'></a></div>");
				}else{
					$("#"+ v_itemId + "_img_queue").append("<div class='uploadify-img-queue-div'>" + 
							"<img src=\""+sy.basePath+"/static/manager/libs/uploadifive/file.png\" style=\"width: 60px; height:60px;\">"+
							"<a class='uploadify-img-queue-div-a' href='javascript:void(0)' onclick='$(\"#"+v_itemId+"\").delFileId(\""+array[i]+"\","+multi+");$(this).parent().remove();'></a></div>");
				}
				
		
			}
		}
	};
	
	sy.initFileUpload();
});

sy.initFileUpload = function(target){
	  //文件上传控件
	  $.each($("input[type=file]"),function(index,obj){
		  	if(target!=undefined) {
		  		if($(obj).attr("id") != target){
		  			return true;
		  		}
		  	}
		  
		  	 var v_init = ("false" != $(obj).attr('init'));
		  	 if(!v_init)return;
	  		 var method = $(obj).attr('onUploadSuccess');
	  		 var showImage = ("true" == $(obj).attr("showImage"));
	  		 var o = obj;
	  		 var v_itemId = $(obj).attr("id");
	  		 var v_multi = ("true" == $(obj).attr('multi'));
	  		 var showBtn=$(obj).attr("showBtn")||'false';
	  		 var bestSize=$(obj).attr("bestSize")||'';
	  		 //if (showImage) {
	  		 	$("#" + v_itemId).before('<div id="' + v_itemId + '_img_queue" style="width:100%;height:100%;"></div><div style="clear:both;"></div>');
	  		 //}
	  		 
	  		var v_required = ("required" == $(obj).attr('required'));
	  		var v_missingMessage = $(obj).attr("missingMessage")||'请上传文件';
	  		$("#" + v_itemId).after("<input id='" + v_itemId + "_hidden' type=\"hidden\" name=\""+v_itemId+"\" "+(v_required?"required":"")+" missingMessage=\""+v_missingMessage+"\"></input>");
	  		$("#" + v_itemId).after("<div id='" + v_itemId + "_queue'></div>");
	  		
	  		var v_fileType = $(obj).attr('fileType') || "";
	  		var v_fileSize = $(obj).attr('fileSize') || "";
	  		var v_fileCountLimit = $(obj).attr("fileCountLimit") || "";
	  		var v_formData = $(obj).attr("formData") || "{}";
	  		v_formData = $.parseJSON(v_formData);
	  		
	  		$(obj).uploadifive({
				'auto' : $(obj).attr('auto')||true,
				'buttonText':$(obj).attr('buttonText')|| "文件上传",
				'formData' : v_formData,
				'queueID' : v_itemId + '_queue',
				'uploadScript' : sy.basePath+'/fileUpload',
		        'multi': true, // 是否支持多文件一起上传
		        'uploadLimit':999,
		        'removeCompleted' : false,
		        'fileType':v_fileType||'*', //允许上传的文件后缀
		        'fileSizeLimit':v_fileSize||'1MB',
		        'removeCompleted' : true,
		        'onUpload':function(cnt){
		        	var ids = $("#"+ v_itemId+"_hidden").val();
		        	var file_cnt = 0;
		    		if(ids == undefined || ids == ''){
		    			file_cnt = 0;
		    		}else{
		    			var array = ids.split(",");
		    			file_cnt = array.length;
		    		}
		        	if (v_fileCountLimit != "" && parseInt(v_fileCountLimit) < file_cnt + cnt) {
		        		if(v_fileCountLimit > 1){
		        			alert("文件上传数量超出限制(" + v_fileCountLimit + "个)");
							$("#" + v_itemId).uploadifive("clearQueue");
							return false;
		        		}
					}
		        },
		        'onFallback' : function() {
					alert("该浏览器不支持上传控件!");
				},
				'onError':function(){
					$("#" + v_itemId).uploadifive("clearQueue");
				},
				'onUploadComplete' : function(file, data) {
					var ret = $.parseJSON(data);
		        	if (ret.error == 0) {
		        		$("#"+v_itemId).setFileId(ret.url,v_multi,showImage,showBtn,bestSize);
		        		// 去除队列信息
	        			$("#" + v_itemId).uploadifive('cancel', file);
		        		if(method!='' && window[method]){
			        		window[method].call(window, ret);
			        	}
		        	}else{	
		        		alert(ret.message);
		        	}
				}
			});
	  });
}

function HtmlEditor(v_id, v_options) {
	if(!v_options)v_options ={};
	var fullItems = ['source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
			        'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
			        'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
			        'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
			        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
			        'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
			         'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
			        'anchor', 'link', 'unlink'
			];
	var easyItems = ['source', '|', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                	'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
                	'insertunorderedlist', '|', 'image', 'link', 'unlink', '|', 'fullscreen'];
	
	// 对外参数
	this.options = {
		uploadJson : 'fileUpload',
		newlineTag : "br",
		filePostName:"Filedata",
		afterUpload : function(url) {
        },
        resizeType : 1,
        pasteType:1,
        items : easyItems,
		formatUploadUrl:true,
		fillDescAfterUploadImage:true
	};
	$.extend(this.options, v_options);

	if (!KindEditor) {
		mini.alert("请先加载htmlEditor的JS文件!");
		return;
	}

	var v_loader = this;

	// 初始化
	this.options.editor = KindEditor.create('#' + v_id, this.options);

	return this;
}
HtmlEditor.prototype = {
	getHtml : function() {
		return this.options.editor.html();
	},
	setHtml : function(v_html) {
		if (v_html != null) {
			return this.options.editor.html(v_html);
		}
	}
};